import logging
import random
import re

from flask import request, abort, make_response, json

from info import redis_store
from info.constants import IMAGE_CODE_REDIS_EXPIRES
from info.response_code import *
from info.utils.captcha.captcha import captcha
from info.utils.yuntongxun import sms
from . import passport_blueprint

@passport_blueprint.route("/image_code")
def image_code():
    """发送验证码图片
    1.先收js发送过来的参数------uuid，唯一标识符
    2.生成图片验证码
    3.将图片验证码文本与uuid放在redis中
    4.将图片返回到html中
    5.设置image返回的content-type，默认为html/text，有些浏览器不智能"""
    print("1111111111111111111111111111111111111111111111")
    imageCodeId = request.args.get("imageCodeId")
    if not imageCodeId:
        return abort(403)
    try:
        name, text,image = captcha.generate_captcha()
    except Exception as e:
        logging.error(e)
        #服务器错误
        return abort(500)
    try:
        redis_store.set("imageCodeId_" + imageCodeId,text,IMAGE_CODE_REDIS_EXPIRES)
    except Exception as e:
        logging.error(e)
        # redis存储错误，服务器错误
        return abort(500)
    response = make_response(image)
    response.headers["Content-Type"] = "image/jpg"
    return response

@passport_blueprint.route("/sendmsg",methods=["POST"])
def sendmsg():
    """将手机号，验证码，uuid值取出来，并且判断是否为空
    先判断手机号是否正确，在去验证码，在判断验证码是否为空，在判断验证码是否正确
    生成短信信息，发送短信   ok"""
    params = request.json
    mobile = params["mobile"]
    imageCode = params["imageCode"]
    imageCodeId = params["imageCodeId"]
    if not all([mobile,imageCode,imageCodeId]):
        return json.jsonify(errno=RET.NODATA,errmsg="参数不正确")
    ret  =re.match(r"1[35678]\d{9}",mobile)
    if not ret:
        return json.jsonify(errno=RET.PARAMERR,errmsg="手机号输入有误")
    try:
        imageCodeId_new = redis_store.get("imageCodeId_" + imageCodeId)
    except Exception as e:
        logging.error(e)
        return json.jsonify(errno=RET.DBERR,errmsg="数据库错误")
    if not imageCodeId_new:
        return json.jsonify(errno=RET.DATAERR,errmsg="验证码输入错误")
    if imageCode.upper() != imageCodeId_new.upper():
        return json.jsonify(errno=RET.NODATA,errmsg="验证码不正确")
    num_srt = "%06d"%random.randint(0,999999)
    result = sms.CCP().send_template_sms('18629188999', [num_srt, IMAGE_CODE_REDIS_EXPIRES / 60], 1)
    if result != 0:
        return json.jsonify(errno=RET.THIRDERR,errmsg="发送验证码失败")
    try:
        redis_store.set(imageCodeId + mobile,num_srt,IMAGE_CODE_REDIS_EXPIRES)
    except Exception as e:
        logging.error(e)
        return json.jsonify(errno=RET.DBERR,errmsg="数据库存储失败")
    return json.jsonify(errno="0",errmsg="成功")